package com.zb.mobile.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zb.constant.RedisSelectDataConstant;
import com.zb.constant.WorkConstant;
import com.zb.excel.converter.WorkConverter;
import com.zb.entity.*;
import com.zb.exception.SMSException;
import com.zb.extend.WorkGoodsExtend;
import com.zb.extend.WorkOrderExtend;
import com.zb.mobile.*;
import com.zb.mobile.user.service.ConUserMobileOrderService;
import com.zb.order.service.ConWorkOrderService;
import com.zb.redis.RedisUtil;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.service.impl.WorkServiceLog;
import com.zb.util.MobileUserSmsUtil;
import com.zb.view.ViewGoods;
import com.zb.view.ViewNetworkEmpAccount;
import com.zb.vo.OrderUserVo;
import com.zb.vo.OrderVo;
import com.zb.vo.WorkLogVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author WEN
 * @Date 2023/11/2 0002
 **/
@Service
public class ConUserMobileOrderServiceImpl implements ConUserMobileOrderService {

    private static final Long DOOR_LOCK_MODULE_ID = 1848175864471171074L;
    private static final Long DONG_DONG_PASS_FACTORY_ID = 1815257689090023425L;

    @Resource
    private ZjWorkOrderService workOrderService;
    @Resource
    private ZjWorkUserService workUserService;
    @Resource
    private ZjWorkGoodsService workGoodsService;
    @Resource
    private ZjWorkGoodsCodeService workGoodsCodeService;
    @Resource
    private ZjWorkModuleService workModuleService;
    @Resource
    private ZjWorkLevelService workLevelService;
    @Resource
    private ZjWorkDetailService workDetailService;
    @Resource
    private ZjWorkLogService workLogService;
    @Resource
    private ZjWorkImageService workImageService;
    @Resource
    private ZjNetworkService networkService;
    @Resource
    private ZjWorkDispatchEngineerService workDispatchEngineerService;
    @Resource
    private ZjWorkDispatchEngineerCooperateService workDispatchEngineerCooperateService;
    @Resource
    private ViewNetworkEmpAccountService viewNetworkEmpAccountService;
    @Resource
    private ConWorkOrderService conWorkOrderService;
    @Resource
    private ViewGoodsService viewGoodsService;
    @Resource
    private ZjWorkEngineerSignService workEngineerSignService;
    @Resource
    private ZjWorkFieldValService workFieldValService;

    // 服务进度-获取工单状态数量，客户ID获取
    @Override
    public Map<String, Object> getOrderStatusQty(Long custAccId, Long userId, UserOrderSelectVo selectVo) throws SMSException {
        if (selectVo.isSelectHelpOtherCreateOrder()) {
            Assert.isTrue(StringUtils.isNotBlank(selectVo.getVerifiCode()), "验证码不能为空");
            if (!RedisUtil.hasKey(RedisSelectDataConstant.USER_ORDER_SELECT + selectVo.getPhone())) {
                MobileUserSmsUtil.checkSelectVerificCode(selectVo.getPhone(), selectVo.getVerifiCode());
                RedisUtil.setCache(RedisSelectDataConstant.USER_ORDER_SELECT + selectVo.getPhone(), selectVo.getPhone(), RedisSelectDataConstant.EXPIRE_TIME);
            }
        }
        Map<String, Object> resultMap = new HashMap<>();
        List<Long> ids = new ArrayList<>();
        if (StringUtils.isNotBlank(selectVo.getKeyword())) {
            List<Long> workIds = workOrderService.getWorkIdByUserMobileSearch(custAccId, userId, selectVo);
            if (CollectionUtil.isEmpty(workIds)) {
                resultMap.put("totalOrderQty", 0);
                resultMap.put("serviceOrderQty", 0);
                resultMap.put("finishOrCancelOrderQty", 0);
                resultMap.put("waitCommentOrderQty", 0);
                return resultMap;
            }
            ids.addAll(workIds);
        }
        selectVo.setStatus(null);
        resultMap.put("totalOrderQty", workOrderService.getUserOrderListCount(custAccId, userId, ids, selectVo));
        selectVo.setStatus(2);
        resultMap.put("serviceOrderQty", workOrderService.getUserOrderListCount(custAccId, userId, ids, selectVo));
        selectVo.setStatus(3);
        resultMap.put("finishOrCancelOrderQty", workOrderService.getUserOrderListCount(custAccId, userId, ids, selectVo));
        selectVo.setStatus(4);
        resultMap.put("waitCommentOrderQty", workOrderService.getUserOrderListCount(custAccId, userId, ids, selectVo));
        return resultMap;
    }

    // 服务进度-获取工单列表
    @Override
    public Map<String, Object> getOrderList(Long custAccId, Long userId, UserOrderSelectVo selectVo) throws SMSException {
        if (selectVo.isSelectHelpOtherCreateOrder()) {
            Assert.isTrue(StringUtils.isNotBlank(selectVo.getVerifiCode()), "验证码不能为空");
            if (!RedisUtil.hasKey(RedisSelectDataConstant.USER_ORDER_SELECT + selectVo.getPhone())) {
                MobileUserSmsUtil.checkSelectVerificCode(selectVo.getPhone(), selectVo.getVerifiCode());
                RedisUtil.setCache(RedisSelectDataConstant.USER_ORDER_SELECT + selectVo.getPhone(), selectVo.getPhone(), RedisSelectDataConstant.EXPIRE_TIME);
            }
        }
        PageUtil.setPageLimitMobile(selectVo);
        List<Long> ids = new ArrayList<>();
        if (StringUtils.isNotBlank(selectVo.getKeyword())) {
            List<Long> workIds = workOrderService.getWorkIdByUserMobileSearch(custAccId, userId, selectVo);
            if (CollectionUtil.isEmpty(workIds)) {
                return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), 0L, new ArrayList<>());
            }
            ids.addAll(workIds);
        }
        List<WorkOrderExtend> orderList = workOrderService.getUserOrderList(custAccId, userId, ids, selectVo);
        List<Long> moduleIds = orderList.stream().map(ZjWorkOrder::getModuleId).distinct().toList();
        List<WorkGoodsExtend> goodsExtends = workGoodsService.getByWorkIds(orderList.stream().map(ZjWorkOrder::getId).toList());
        List<ZjWorkModule> moduleList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(moduleIds)) {
            moduleList.addAll(workModuleService.listByIds(moduleIds));
        }
        List<UserOrderListVo> voList = orderList.stream().map(o -> {
            UserOrderListVo vo = new UserOrderListVo();
            BeanUtil.copyProperties(o, vo);
            vo.setWorkNo(o.getCode());
            vo.setCreateTime(o.getGmtCreate());
            vo.setUpdateTime(o.getGmtUpdate());
            vo.setModule(moduleList.stream().filter(f -> Objects.equals(f.getId(), o.getModuleId())).map(mo -> {
                return "【" + WorkConverter.moduleTypeConverter(mo.getType()) + "】" + mo.getName();
            }).findFirst().orElse(""));
//            vo.setOrderGoods(goodsExtends.stream().filter(f -> Objects.equals(f.getWorkId(), o.getId())).map(goods -> {
//                UserOrderGoodsVo goodsVo = new UserOrderGoodsVo();
//                BeanUtil.copyProperties(goods, goodsVo);
//                return goodsVo;
//            }).toList());
            return vo;
        }).toList();
        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), workOrderService.getUserOrderListCount(custAccId, userId, ids, selectVo), voList);
    }

    // 服务进度-根据工单ID获取工单列表详情
    @Override
    public UserOrderDetailVo  getOrderDetail(Long workId) {
        ZjWorkOrder order = workOrderService.getById(workId);
        Assert.isTrue(null != order, "工单ID参数["+ workId +"]的数据不存在");
        UserOrderDetailVo vo = new UserOrderDetailVo();
        BeanUtil.copyProperties(order, vo);
        vo.setWorkNo(order.getCode());
        vo.setCreateTime(order.getGmtCreate());
        vo.setUpdateTime(order.getGmtUpdate());
        ZjWorkDetail workDetail = workDetailService.getById(order.getId());
        vo.setReservationDate(workDetail.getReservationDate());
        vo.setReservationStartTime(workDetail.getReservationStartTime());
        vo.setReservationEndTime(workDetail.getReservationEndTime());

        vo.setEngineerServiceTime(workEngineerSignService.getSignTimeByWorkIdAndNetworkEmpId(workId, order.getNetworkEmpId()));

        ZjWorkModule module = workModuleService.getById(order.getModuleId());
        vo.setModule("【" + WorkConverter.moduleTypeConverter(module.getType()) + "】" + module.getName());

        ZjWorkLevel level = workLevelService.getById(order.getWorkLevelId());
        if (null != level) {
            vo.setLevel(level.getName());
            vo.setLevelColor(level.getColor());
        }
        return vo;
    }

    // 服务进度-根据工单ID获取工单列表详情的服务进度
    @Override
    public Map<String, Object> getOrderServiceLog(Long workId, PageUtil pageUtil) {
        PageUtil.setPageLimitMobile(pageUtil);
        return workLogService.getOrderLogList(workId, pageUtil);
    }

    // 服务进度-获取工单列表详情的商品信息
    @Override
    public List<UserOrderGoodsVo> getOrderDetailGoodsInfo(Long workId) {
        List<WorkGoodsExtend> extendList = workGoodsService.getByWorkId(workId);

        List<Long> workGoodIds = extendList.stream().map(WorkGoodsExtend::getId).toList();
        List<ZjWorkGoodsCode> goodsCodeList = workGoodsCodeService.getByWorkGoodsIds(workGoodIds);
        return extendList.stream().map(extend -> {
            UserOrderGoodsVo vo = new UserOrderGoodsVo();
            BeanUtil.copyProperties(extend, vo);
            vo.setCodes(goodsCodeList.stream().filter(f -> Objects.equals(f.getWorkGoodsId(), extend.getId())).map(ZjWorkGoodsCode::getCode).toList());
            return vo;
        }).toList();
    }

    // 服务进度-获取工单列表详情的工单信息
    @Override
    public UserOrderInfoVo getOrderDetailOrderInfo(Long workId) {
        ZjWorkDetail workDetail = workDetailService.getById(workId);
        Assert.isTrue(null != workDetail, "工单ID参数["+ workId +"]工单信息数据不存在");
        UserOrderInfoVo vo = new UserOrderInfoVo(workDetail.getContent(), workImageService.getByWorkId(workId).stream().map(ZjWorkImage::getImage).toList());
        vo.setOrderCustomFields(workFieldValService.getOrderFieldParam(workId));
        return vo;
    }

    // 服务进度-获取工单列表详情的服务商信息
    @Override
    public UserOrderNetworkInfo getOrderDetailNetworkInfo(Long workId) {
        ZjWorkOrder workOrder = workOrderService.getById(workId);
        Assert.isTrue(null != workOrder, "工单ID参数["+ workId +"]的工单数据不存在");

        UserOrderNetworkInfo networkInfo = new UserOrderNetworkInfo();
        ZjNetwork network = networkService.getById(workOrder.getNetworkId());
        networkInfo.setNetwork(null != network? network.getName() : "");
        ZjWorkDispatchEngineer dispatchEngineer = workDispatchEngineerService.getByWorkIdAndNetworkIdAndNetworkEmpId(workId, workOrder.getNetworkId(), workOrder.getNetworkEmpId());
        if (null != dispatchEngineer) {
            ViewNetworkEmpAccount empAccount = viewNetworkEmpAccountService.getById(dispatchEngineer.getNetworkEmpId());
            networkInfo.setEngineerName(empAccount.getName());
            networkInfo.setEngineerPhone(empAccount.getPhone());

            List<ZjWorkDispatchEngineerCooperate> cooperateList = workDispatchEngineerCooperateService.getByWorkDispatchEngineerId(dispatchEngineer.getId());
            List<Long> networkEmpIds = cooperateList.stream().map(ZjWorkDispatchEngineerCooperate::getNetworkEmpId).distinct().toList();
            List<ViewNetworkEmpAccount> empAccounts = viewNetworkEmpAccountService.getByIds(networkEmpIds);
            networkInfo.setCooperateEngineer(empAccounts.stream().map(o -> {
                return o.getName() + "  " + o.getPhone();
            }).toList());
        }
        return networkInfo;
    }

    // 服务进度-获取工单列表详情的客户信息
    @Override
    public OrderUserVo getOrderDetailUserInfo(Long workId) {
        ZjWorkUser workUser = workUserService.getById(workId);
        Assert.isTrue(null != workUser, "工单ID参数["+ workId +"]的工单客户数据不存在");
        OrderUserVo vo = new OrderUserVo();
        BeanUtil.copyProperties(workUser, vo);
        return vo;
    }

    // 服务进度-取消服务工单
    @Override
    public void cancelOrder(AccounLoginInfo loginInfo, Long workId) {
        ZjWorkOrder workOrder = workOrderService.getById(workId);
        Assert.isTrue(null != workOrder, "工单ID参数["+ workId +"]的工单数据不存在");
        Assert.isTrue(workOrder.getStatus() == WorkConstant.WORK_STATUS_1, "当前工单已在服务中，不可取消服务工单");

        ZjWorkOrder order = new ZjWorkOrder();
        order.setId(workId);
        order.setStatus(WorkConstant.WORK_STATUS_5);
        order.setCancelTime(new Date());
        order.setNewAdvance(workOrder.getNewAdvance() + 1);
        order.setUpdateEmpId(0L);
        order.setUpdateEmp(loginInfo.getName());
        workOrderService.updateById(order);
        WorkServiceLog.saveOrderUser(new WorkLogVo(loginInfo, workId, "工单客户取消工单", ""));
    }

    // 服务进度-改约日期时间
    @Override
    public void updateExpectedTime(AccounLoginInfo loginInfo, UserOrderExpectedTimeVo orderExpectedTimeVo) {
        ZjWorkOrder workOrder = workOrderService.getById(orderExpectedTimeVo.getWorkId());
        Assert.isTrue(null != workOrder, "服务工单数据不存在");
        Assert.isTrue(orderExpectedTimeVo.getExpectedEndTime().after(orderExpectedTimeVo.getExpectedStartTime()), "期望上门服务结束时间必须大于开始时间");

        ZjWorkOrder order = new ZjWorkOrder();
        order.setId(orderExpectedTimeVo.getWorkId());
        order.setExpectedDate(orderExpectedTimeVo.getExpectedDate());
        order.setExpectedStartTime(orderExpectedTimeVo.getExpectedStartTime());
        order.setExpectedEndTime(orderExpectedTimeVo.getExpectedEndTime());
        order.setNewAdvance(workOrder.getNewAdvance() +1);
        workOrderService.updateById(order);
        StringBuilder builder = new StringBuilder();
        builder.append(DateUtil.format(orderExpectedTimeVo.getExpectedDate(), "yyyy-MM-dd")).append(" ")
                .append(DateUtil.format(orderExpectedTimeVo.getExpectedStartTime(), "HH:mm")).append(" ~ ")
                .append(DateUtil.format(orderExpectedTimeVo.getExpectedEndTime(), "HH:mm"));
        if (StringUtils.isNotBlank(orderExpectedTimeVo.getRemark())) {
            builder.append("；备注：").append(orderExpectedTimeVo.getRemark());
        }
        WorkServiceLog.saveOrderUser(new WorkLogVo(loginInfo, orderExpectedTimeVo.getWorkId(), "更改客户期望上门服务时间", builder.toString()));
    }

    // 历史工单报单-历史工单列表
    @Override
    public Map<String, Object> getUserHistoryOrder(AccounLoginInfo loginInfo, SelectVo selectVo) {
        PageUtil.setPageLimitMobile(selectVo);
        List<Long> ids = new ArrayList<>();
        if (StringUtils.isNotBlank(selectVo.getName())) {
           List<Long> workIds = workGoodsService.getWorkIdByGoodsName(loginInfo.getCustAccId(), selectVo.getName());
           if (CollectionUtil.isEmpty(workIds)) workIds.add(0L);
           ids.addAll(workIds);
        }
        List<ZjWorkOrder> orders = workOrderService.getUserMobileHistoryOrder(loginInfo.getCustAccId(), loginInfo.getId(),ids, selectVo);
        if (CollectionUtil.isEmpty(orders)) {
            return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), 0L, new ArrayList<>());
        }
        List<Long> workIds = orders.stream().map(ZjWorkOrder::getId).toList();
        List<Long> moduleIds = orders.stream().map(ZjWorkOrder::getModuleId).distinct().toList();
        List<ZjWorkModule> moduleList = workModuleService.getPartInfoByIds(moduleIds);

        QueryWrapper<ZjWorkUser> workUserQueryWrapper = new QueryWrapper<>();
        workUserQueryWrapper.select("id", "is_help_other_create_order AS helpOtherCreateOrder");
        workUserQueryWrapper.in("id", workIds);
        List<ZjWorkUser> userList = workUserService.list(workUserQueryWrapper);

        List<UserHistoryOrderListVo> voList = orders.stream().map(o -> {
            UserHistoryOrderListVo vo = new UserHistoryOrderListVo();
            BeanUtil.copyProperties(o, vo);
            vo.setWorkNo(o.getCode());
            moduleList.stream().filter(f -> Objects.equals(f.getId(), o.getModuleId())).findFirst().ifPresent(module -> vo.setModule("【" + WorkConverter.moduleTypeConverter(module.getType()) + "】" + module.getName()));
            vo.setCreateTime(o.getGmtCreate());
            userList.stream().filter(f -> Objects.equals(f.getId(), o.getId())).findFirst().ifPresent(workUser -> {
                vo.setHelpOtherCreateOrder(workUser.getHelpOtherCreateOrder());
            });
            return vo;
        }).toList();
        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), workOrderService.getUserMobileHistoryOrderCount(loginInfo.getCustAccId(), loginInfo.getId(),ids), voList);
    }

    // 历史工单报单-历史工单列表详情
    @Override
    public UserHistoryOrderDetailVo getUserHistoryOrderDetail(Long workId) {
        ZjWorkOrder workOrder = workOrderService.getById(workId);
        Assert.isTrue(null != workOrder, "服务工单数据不存在");
        ZjWorkUser workUser = workUserService.getById(workId);
        ZjWorkModule module = workModuleService.getById(workOrder.getModuleId());
        ZjWorkLevel level = workLevelService.getById(workOrder.getWorkLevelId());

        UserHistoryOrderDetailVo vo = new UserHistoryOrderDetailVo();
        BeanUtil.copyProperties(workOrder, vo);
        vo.setWorkNo(workOrder.getCode());
        vo.setHelpOtherCreateOrder(workUser.getHelpOtherCreateOrder());
        vo.setModule("【" + WorkConverter.moduleTypeConverter(module.getType()) + "】" + module.getName());
        if (null != level) {
            vo.setWorkLevel(level.getName());
            vo.setWorkLevelColor(level.getColor());
        }
        vo.setCreateTime(workOrder.getGmtCreate());
//        vo.setWorkNo(workOrder.getCode());
//        vo.setCreateTime(workOrder.getGmtCreate());
//        vo.setUpdateTime(workOrder.getGmtUpdate());
//        vo.setHelpOtherCreateOrder(workUser.getHelpOtherCreateOrder());
//        if (workUser.getHelpOtherCreateOrder()) vo.setOtherUserId(workUser.getUserId());
//
//        ZjWorkModule module = workModuleService.getById(workOrder.getModuleId());
//        vo.setModule("【" + WorkConverter.moduleTypeConverter(module.getType()) + "】" + module.getName());

//        ZjWorkLevel level = workLevelService.getById(workOrder.getWorkLevelId());
//        if (null != level) {
//            vo.setLevel(level.getName());
//            vo.setLevelColor(level.getColor());
//        }
//        List<WorkGoodsExtend> extendList = workGoodsService.getByWorkId(workId);
//        List<Long> workGoodsIds = extendList.stream().map(WorkGoodsExtend::getId).toList();
//        List<ZjWorkGoodsCode> goodsCodeList = workGoodsCodeService.getByWorkGoodsIds(workGoodsIds);
//        vo.setOrderGoods(extendList.stream().map(g -> {
//            UserHistoryOrderDetaiGoodsVo goodsVo = new UserHistoryOrderDetaiGoodsVo();
//            BeanUtil.copyProperties(g, goodsVo);
//            goodsVo.setGoodsCodes(goodsCodeList.stream().filter(f -> Objects.equals(f.getWorkGoodsId(), g.getId())).map(co -> {
//                return new OrderGoodsCodeVo(co.getCodeId(), co.getCode());
//            }).toList());
//            return goodsVo;
//        }).toList());
        return vo;
    }

    // 历史工单报单-历史工单商品信息
    @Override
    public Map<String, Object> getUserHistoryOrdeGoods(Long workId, PageUtil pageUtil) {
        PageUtil.setPageLimitMobile(pageUtil);
        QueryWrapper<ZjWorkGoods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.select("id", "goods_id", "goods_spec_id", "qty");
        goodsQueryWrapper.eq("work_id", workId);
        Page<ZjWorkGoods> page = workGoodsService.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), goodsQueryWrapper);
        List<Long> goodsIds = page.getRecords().stream().map(ZjWorkGoods::getGoodsId).distinct().toList();
        List<Long> goodsSpecIds = page.getRecords().stream().map(ZjWorkGoods::getGoodsSpecId).distinct().toList();
        List<ViewGoods> viewGoodsList = viewGoodsService.getByGoodsIdsAndGoodsSpecIds(goodsIds, goodsSpecIds);
        List<ZjWorkGoodsCode> goodsCodeList = workGoodsCodeService.getByWorkGoodsIds(page.getRecords().stream().map(ZjWorkGoods::getId).toList());

        List<UserHistoryOrderDetaiGoodsVo> voList = page.getRecords().stream().map(goods -> {
            UserHistoryOrderDetaiGoodsVo vo = new UserHistoryOrderDetaiGoodsVo();
            vo.setId(goods.getId());
            vo.setGoodsId(goods.getGoodsId());
            vo.setGoodsSpecId(goods.getGoodsSpecId());
            vo.setQty(goods.getQty());
            viewGoodsList.stream().filter(f -> Objects.equals(1, f.getGoodsType()) && Objects.equals(f.getId(), goods.getGoodsId()) && Objects.equals(f.getSpecId(), goods.getGoodsSpecId()))
                    .findFirst().ifPresent(specView -> {
                        vo.setGoodsBrand(specView.getBrand());
                        vo.setGoodsName(specView.getName());
                        vo.setGoodsModel(specView.getModel());
                        vo.setGoodsType(specView.getType());
                        vo.setGoodsSpecName(specView.getSpecName());
                        vo.setGoodsImage(specView.getImage());
                    });
            goodsCodeList.stream().filter(f -> Objects.equals(f.getWorkGoodsId(), goods.getId())).findFirst().ifPresent(co -> vo.setCode(co.getCode()));
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 历史工单报单-历史工单商品编码信息
    @Override
    public List<OrderGoodsCodeVo> getUserHistoryOorderGoodsCodes(Long workGoodsId) {
        QueryWrapper<ZjWorkGoodsCode> wrapper = new QueryWrapper<>();
        wrapper.select("code_id", "code");
        wrapper.eq("work_goods_id", workGoodsId);
        List<ZjWorkGoodsCode> goodsCodeList = workGoodsCodeService.list(wrapper);

        List<OrderGoodsCodeVo> voList = goodsCodeList.stream().map(code -> {
            OrderGoodsCodeVo vo = new OrderGoodsCodeVo();
            vo.setCodeId(code.getCodeId());
            vo.setCode(code.getCode());
            return vo;
        }).toList();
        return voList;
    }

    // 历史工单报单-获取历史工单申请售后的商品
    @Override
    public UserHistoryOrderApplySaleVo gettUerHistoryOrderApplySale(Long workId) {
        ZjWorkOrder order = workOrderService.getById(workId);
        Assert.notNull(order, "服务工单数据不存在");
        ZjWorkUser workUser = workUserService.getById(workId);

        UserHistoryOrderApplySaleVo vo = new UserHistoryOrderApplySaleVo();
        BeanUtil.copyProperties(workUser, vo);
        vo.setOverinsured(order.getOverinsured());
        vo.setUserName(workUser.getName());
        vo.setUserPhone(workUser.getPhone());

        List<WorkGoodsExtend> goodsExtendList = workGoodsService.getByWorkId(workId);
        List<Long> workGoodIds = goodsExtendList.stream().map(WorkGoodsExtend::getId).toList();
        List<ZjWorkGoodsCode> goodsCodeList = workGoodsCodeService.getByWorkGoodsIds(workGoodIds);
        vo.setGoodsVos(goodsExtendList.stream().map(goods -> {
            UserHistoryOrderDetaiGoodsVo goodsVo = new UserHistoryOrderDetaiGoodsVo();
            BeanUtil.copyProperties(goods, goodsVo);
            goodsVo.setGoodsCodes(goodsCodeList.stream().filter(f -> Objects.equals(f.getWorkGoodsId(), goods.getId())).map(code -> {
                OrderGoodsCodeVo codeVo = new OrderGoodsCodeVo();
                codeVo.setCodeId(code.getCodeId());
                codeVo.setCode(code.getCode());
                return codeVo;
            }).toList());
            return goodsVo;
        }).toList());
        return vo;
    }

    // 移动端客户报单
    @Override
    public Map<String, Object> saveUserOrder(AccounLoginInfo loginInfo, UserOrderVo userOrderVo) {
        ZjWorkModule module = workModuleService.getById(userOrderVo.getModuleId());
        Assert.isTrue(null != module, "报单的模块类型参数的数据不存在");
        Long levelId = workLevelService.getDefaultLevelIdByCustAccId(loginInfo.getCustAccId());

        OrderVo orderVo = new OrderVo();
        orderVo.setId(null);
        orderVo.setFactoryId(null == userOrderVo.getFactoryId()? 0L : userOrderVo.getFactoryId());
        //工单模块为门锁报修码时，品牌商家写死咚咚通行
        if (DOOR_LOCK_MODULE_ID.equals(userOrderVo.getModuleId())) orderVo.setFactoryId(DONG_DONG_PASS_FACTORY_ID);
        orderVo.setModuleId(userOrderVo.getModuleId());
        orderVo.setCollectCustomerPrice(userOrderVo.getCollectCustomerPrice());
        orderVo.setEmpId(0L);
        orderVo.setNetworkId(0L);
        orderVo.setOverinsured(userOrderVo.isHistoryOrder()? userOrderVo.getOverinsured() : module.getOverinsured());
        orderVo.setSource(WorkConstant.WORK_SOURCE_2);
        orderVo.setWorkLevelId(levelId);
        orderVo.setExpectedDate(userOrderVo.getExpectedDate());
        orderVo.setExpectedStartTime(userOrderVo.getExpectedStartTime());
        orderVo.setExpectedEndTime(userOrderVo.getExpectedEndTime());
        orderVo.setContent(userOrderVo.getContent());
        orderVo.setCollectCustomerPriceVoucher(userOrderVo.getCollectCustomerPriceVoucher());
        orderVo.setCreateTime(new Date());
        orderVo.setImageVos(userOrderVo.getImages());

        OrderUserVo orderUser = userOrderVo.getOrderUser();
        if (!orderUser.getHelpOtherCreateOrder()) {
            orderUser.setUserId(loginInfo.getId());
        }
        orderVo.setOrderUser(orderUser);
        orderVo.setOrderGoodsTypes(userOrderVo.getOrderGoodsTypes());
        orderVo.setWorkFieldVal(userOrderVo.getWorkFieldVal());
        return conWorkOrderService.save(loginInfo, true, orderVo);
    }

}
